package com.gj.demojuc.chap04;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * 首先以List作为演示对象，创建多个线程，对List接口的常用实现类ArrayList进行add操作。
 */
public class NotSafeDemo {
    public static void main(String[] args) {
        notSafeList();
        System.out.println("===================");
        notSafeSet();
        System.out.println("===================");
        notSafeMap();
    }

    public static void notSafeList(){
        //        List<String> list = new ArrayList<>();
        //改为Vector或者synchronizedList
//        List<String> list = Collections.synchronizedList(new ArrayList<>()); 缺点：迭代器线程不安全
        //2倍内存空间 数据不一致短暂的
        List<String> list = new CopyOnWriteArrayList<>();
        for (int i = 0; i < 100; i++) {
            new Thread(()->{
                list.add(UUID.randomUUID().toString());
                System.out.println(list);
            }).start();
        }
    }
    public static void notSafeSet(){
        Set<String> set = new CopyOnWriteArraySet<>();
        for (int i = 0; i < 100; i++) {
            new Thread(()->{
                set.add(UUID.randomUUID().toString().substring(0,8));
                System.out.println(set);
            },String.valueOf(i)).start();
        }
    }

    public static void notSafeMap(){
        Map<String,String> map = new ConcurrentHashMap<>();
        for (int i = 0; i < 100; i++) {
            new Thread(()->{
                map.put(String.valueOf(Thread.currentThread().getName()),UUID.randomUUID().toString().substring(0,8));
                System.out.println(map);
            },String.valueOf(i)).start();
        }
    }
}
